from rest_framework import serializers

from goods.models import SKU


class CartSerializer(serializers.Serializer):
    """购物车序列化器"""

    sku_id = serializers.IntegerField(label='sku id', min_value=1)
    count = serializers.IntegerField(label='数量', min_value=1)
    selected = serializers.BooleanField(label='是否勾选', default=True)

    def validate_sku_id(self, value):
        """校验前段传的id是否存在"""
        try:
            sku = SKU.objects.get(id=value)
        except SKU.DoesNotExist:
            raise serializers.ValidationError('sku_id 不存在')

        return value


class CartSKUSerializer(serializers.ModelSerializer):
    """
    购物车商品数据序列化
    """
    count = serializers.IntegerField(label='数量')
    selected = serializers.BooleanField(label='是否勾选')

    class Meta:
        model = SKU
        fields = ['id', 'count', 'name', 'default_image_url', 'price', 'selected']


class CartDeleteSerializer(serializers.Serializer):
    """删除购物车序列化器"""
    sku_id = serializers.IntegerField(label='商品SKU ID', min_value=1)

    def validate(self, attrs):
        sku_id = attrs.get('sku_id')
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            raise serializers.ValidationError

        return attrs


class CartSelectAllSerializer(serializers.Serializer):
    """购物车全选"""
    selected = serializers.BooleanField(label='是否 全选')
